package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.StrategyTags;
import cn.wolfcode.trip.base.mapper.StrategyTagsMapper;
import cn.wolfcode.trip.base.service.IStrategyTagsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author 10303
 * @Title: StrategyTagsServiceImpl
 * @ProjectName parent
 * @Description: TODO
 * @date 2018/11/1716:01
 */
@Service
public class StrategyTagsServiceImpl implements IStrategyTagsService {
    @Autowired
    private StrategyTagsMapper strategyTagsMapper;


    @Override
    public void saveOrUpdate(Long strategyId, String[] tags, String[] myTags) {
        //首先将数组合并
        int str1Length = tags.length;
        int str2length = myTags.length;
        tags = Arrays.copyOf(tags, str1Length+str2length);//数组扩容
        System.arraycopy(myTags, 0, tags, str1Length, str2length);


        if(tags.length != 0){
            for (String tag : tags) {
                //根据攻略id和标签名查看对象是否存在
                StrategyTags oldTag = strategyTagsMapper.selectTagByStrategyId(strategyId, tag);
                if(oldTag == null) {
                    //新建标签对象
                    StrategyTags newTag = new StrategyTags();
                    newTag.setCount(1);
                    newTag.setCreateTime(new Date());
                    newTag.setStrategyId(strategyId);
                    newTag.setTag(tag);
                    //保存
                    strategyTagsMapper.insert(newTag);
                }else {
                    oldTag.setCount(oldTag.getCount() + 1);
                    strategyTagsMapper.updateByPrimaryKey(oldTag);
                }
            }
        }

    }

    @Override
    public List<StrategyTags> listNeedByStrategyId(Long strategyId) {
        return strategyTagsMapper.selectNeedByStrategyId(strategyId);
    }
}
